#include <iostream>
#include <vector>
#include <list>

#include <TROOT.h>
#include <TFile.h>
#include <TTree.h>
#include <TH1D.h>
#include <TCanvas.h>
#include <TVector3.h>

#include "GeomSvc.h"
#include "TriggerRoad.h"
#include "TriggerAnalyzer.h"

using namespace std;

int main(int argc, char* argv[])
{
  GeomSvc* p_geomSvc = GeomSvc::instance();
  p_geomSvc->init("geometry_R962");

  TriggerAnalyzer* triggerAna = new TriggerAnalyzer();
  triggerAna->init("roads_DY.root", 0., 0.);
  triggerAna->buildTriggerTree();

  list<TriggerRoad> p_roads = triggerAna->getRoadsAll(+1);
  list<TriggerRoad> m_roads = triggerAna->getRoadsAll(-1);

  int nHits;
  int detectorID[500];
  int elementID[500];

  TFile* dataFile = new TFile(argv[1], "READ");
  TTree* dataTree = (TTree*)dataFile->Get("save");

  dataTree->SetBranchAddress("nHits", &nHits);
  dataTree->SetBranchAddress("detectorID", detectorID);
  dataTree->SetBranchAddress("elementID", elementID);

  double factor = 50E6/dataTree->GetEntries();
  cout << "Scale factor to real frequency is: " << factor << endl;
  for(int i = 0; i < dataTree->GetEntries(); i++)
    {
      dataTree->GetEntry(i);
      triggerAna->acceptEvent(nHits, detectorID, elementID);

      list<TriggerRoad> p_roads_found = triggerAna->getRoadsFound(+1);
      for(list<TriggerRoad>::iterator iter = p_roads_found.begin(); iter != p_roads_found.end(); ++iter)
	{
	  list<TriggerRoad>::iterator p_road_found = find(p_roads.begin(), p_roads.end(), *iter);
	  if(p_road_found != p_roads.end()) 
	    {
	      p_road_found->rndf += 1.;
	    }
	}

      list<TriggerRoad> m_roads_found = triggerAna->getRoadsFound(-1);
      for(list<TriggerRoad>::iterator iter = m_roads_found.begin(); iter != m_roads_found.end(); ++iter)
	{
	  list<TriggerRoad>::iterator m_road_found = find(m_roads.begin(), m_roads.end(), *iter);
	  if(m_road_found != m_roads.end())
	    {
	      m_road_found->rndf += 1.;
	    }
	}
    }

  TriggerRoad* road = new TriggerRoad(); road->clear();

  TFile* saveFile = new TFile(argv[2], "recreate");
  TTree* saveTree1 = new TTree("single_p", "single_p");
  saveTree1->Branch("road", &road, 256000, 99);

  for(list<TriggerRoad>::iterator iter = p_roads.begin(); iter != p_roads.end(); ++iter)
    {
      *road = *iter;
      road->rndf = road->rndf*factor;
      saveTree1->Fill();
    }

  TTree* saveTree2 = new TTree("single_m", "single_m");
  saveTree2->Branch("road", &road, 256000, 99);

  for(list<TriggerRoad>::iterator iter = m_roads.begin(); iter != m_roads.end(); ++iter)
    {
      *road = *iter;
      road->rndf = road->rndf*factor;
      saveTree2->Fill();
    }

  saveFile->cd();
  saveTree1->Write();
  saveTree2->Write();
  saveFile->Close();

  delete triggerAna;

  return 1;
}
